package com.shelpe.services.tenant.configuration;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
@EnableTransactionManagement
@MapperScan("com.shelpe.services.tenant.dao")
public class MySqlConfiguration {

	@Bean
    public DataSource dataSource(DataSourceProperties props) {
		DruidDataSource ds = new DruidDataSource();
		if(props != null){
			ds.setDriverClassName(props.getDriverClassName());
			ds.setUrl(props.getUrl());
			ds.setUsername(props.getUsername());
			ds.setPassword(props.getPassword());
		}
        return ds;
    }
	
 
    @Bean
    public PlatformTransactionManager txManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
 
    @Bean
    public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
 
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
 
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
 
        sqlSessionFactoryBean.setMapperLocations(resolver
                .getResources("classpath:/sqlmaps/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }
	
}
